package com.kyzh.core.pager.weal.accountbuy

import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.gushenge.core.beans.Deal1
import com.gushenge.core.beans.Sort
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.requests.GameRequest
import com.kyzh.core.R
import com.kyzh.core.activities.BaseFragmentActivity
import com.kyzh.core.adapters.GameDetailDea1lAdapter
import com.kyzh.core.databinding.FragmentAccountbuyBinding
import com.kyzh.core.databinding.HeaderAccountbuyBinding
import com.kyzh.core.databinding.ItemBuytopBinding
import com.gushenge.core.base.fragment.BaseFragment
import com.kyzh.core.utils.dip
import com.kyzh.core.utils.startActivity

class AccountBuyFragment : BaseFragment() {
    private lateinit var db : FragmentAccountbuyBinding
    private lateinit var header : HeaderAccountbuyBinding
    private lateinit var topList :ArrayList<Sort>
    private val topAdapter = TopAdapter()
    private val adapter = GameDetailDea1lAdapter(arrayListOf(),1)
    private var mp = 1
    private var msort = 0
    private var selectTop = 0
    private var smoney = ""
    private var emoney = ""
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        db  = FragmentAccountbuyBinding.inflate(inflater)
        header = HeaderAccountbuyBinding .inflate(inflater)
        return db.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        topList = arrayListOf(Sort(name="全部",isSelect = true),Sort(name="0~50元"),Sort(name="51~100元"),Sort(name="100元以上"))

        initView()
    }

    private fun initView() {

        header.revMoney.layoutManager = LinearLayoutManager(requireContext(),RecyclerView.HORIZONTAL,false)
        header.revMoney.adapter = topAdapter
        topAdapter.setOnItemClickListener { adapter, _, position ->
            selectTop = position
            adapter.notifyItemChanged( resetTop())
            topList[position].isSelect = true
            adapter.notifyItemChanged( position)
            getSearch(header.edtSearch.text.toString().trim())
        }
        topAdapter.setNewInstance(topList)
        getSearch("")
        db.rev.layoutManager = LinearLayoutManager(requireContext())
        db.rev.adapter = adapter
        adapter.loadMoreModule.setOnLoadMoreListener {
            mp++
            GameRequest.getAccountList(1,0,mp,smoney,emoney,header.edtSearch.text.toString().trim(),0){
                this?.apply {
                    adapter.addData(this.data)
                    adapter.loadMoreModule.loadMoreComplete()
                    if(max_p<=mp){
                        adapter.loadMoreModule.loadMoreEnd(true)
                    }
                }
            }
        }
        header.edtSearch.addTextChangedListener {
            if(it.isNullOrBlank()){
                getSearch("")
            }else{
                hander.removeMessages(1)
                val obtainMessage = hander.obtainMessage()
                obtainMessage.obj = it
                obtainMessage.what = 1
                hander.sendMessageAtTime(obtainMessage,1000)
            }

        }
        adapter.setOnItemClickListener { adapter, _, position ->
            val deal = adapter.data[position] as Deal1
            startActivity<BaseFragmentActivity>(
                GlobalKeys.TYPE to BaseFragmentActivity.DEAL_PRODUCT_DETAIL,
                GlobalKeys.KEY to deal.id
            )

        }
        adapter.removeAllHeaderView()
        adapter.addHeaderView(header.root)
        pop()
    }

    private fun pop() {
        header.tv1.setOnClickListener {
            val inflater = requireActivity().getSystemService(AppCompatActivity.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            val contentview: View = inflater.inflate(R.layout.pop_account, null)
            val new = contentview.findViewById<TextView>(R.id.tvNew)
            val desc = contentview.findViewById<TextView>(R.id.tvAccountDesc)
            val asc = contentview.findViewById<TextView>(R.id.tvAccountAsc)
            sortStatus(new,desc,asc)
            val popupWindow = PopupWindow(
                contentview, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            new.setOnClickListener {
                popupWindow.dismiss()
                msort = 0
                sortStatus(new,desc,asc)
                getSearch(header.edtSearch.text.toString().trim())
            }
            desc.setOnClickListener {
                popupWindow.dismiss()
                msort = 1
                sortStatus(new,desc,asc)
                getSearch(header.edtSearch.text.toString().trim())
            }
            asc.setOnClickListener {
                popupWindow.dismiss()
                msort = 2
                sortStatus(new,desc,asc)
                getSearch(header.edtSearch.text.toString().trim())

            }
            contentview.isFocusable = true
            contentview.isFocusableInTouchMode = true

            popupWindow.apply {
                width =dip(110)
                height = dip(108)
                isOutsideTouchable = true
                showAsDropDown( header.tv1)
            }
        }
    }
    private  fun sortStatus (new:TextView,desc:TextView,asc:TextView){
        when(msort){
            0 ->{
                header.tv1.text = new.text
                new.setTextColor(Color.parseColor("#FA8C08"))
                desc.setTextColor(requireActivity().resources.getColor(R.color.font_44))
                asc.setTextColor(requireActivity().resources.getColor(R.color.font_44))
            }
            1 ->{
                header.tv1.text = desc.text
                new.setTextColor(requireActivity().resources.getColor(R.color.font_44))
                desc.setTextColor(Color.parseColor("#FA8C08"))
                asc.setTextColor(requireActivity().resources.getColor(R.color.font_44))
            }
            2 ->{
                header.tv1.text = asc.text
                new.setTextColor(requireActivity().resources.getColor(R.color.font_44))
                desc.setTextColor(requireActivity().resources.getColor(R.color.font_44))
                asc.setTextColor(Color.parseColor("#FA8C08"))
            }
        }
    }
    // 加下拉刷新会印象  就删了
    private fun resetTop():Int{
        topList.forEachIndexed { index, sort ->
            if(sort.isSelect){
                sort.isSelect = false
                return  index
            }
        }
        return 0
    }
   private  class TopAdapter:BaseQuickAdapter<Sort,BaseDataBindingHolder<ItemBuytopBinding>>(
        R.layout.item_buytop){
        override fun convert(holder: BaseDataBindingHolder<ItemBuytopBinding>, item: Sort) {
            holder.dataBinding?.data = item
            if(item.isSelect){
                holder.dataBinding?.tv?.setTextColor(Color.WHITE)
                holder.dataBinding?.tv?.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#FA8C08"))
            }else{
                holder.dataBinding?.tv?.setTextColor(Color.parseColor("#333333"))
                holder.dataBinding?.tv?.backgroundTintList = ColorStateList.valueOf(Color.WHITE)
            }
        }
    }

    private fun getSearch(keyword : String){
        mp = 1
        when(selectTop){
            0 ->{
                smoney =""
                emoney =""
            }
            1 ->{
                smoney ="0"
                emoney ="50"
            }
            2 ->{
                smoney ="50"
                emoney ="100"
            }
            3 ->{
                smoney ="100"
                emoney ="999999"
            }
        }
        GameRequest.getAccountList(1,0,1,smoney,emoney,keyword,msort){
            this?.apply {
                adapter.setNewInstance(this.data)
                adapter.loadMoreModule.loadMoreComplete()
                if(max_p<=mp){
                    adapter.loadMoreModule.loadMoreEnd(true)
                }
            }
        }
    }

    private val hander  = Handler() {
        if(it.what ==1){
            getSearch(it.obj.toString() )
        }
        true
    }

}